<template>
    <div>
        <div class="mb-2">
            <el-button type="primary" @click="showNew" icon="Plus" v-perm="'new'">添加</el-button>
        </div>
        <base-table :fields="fields" :dataSupplier="loadData" ref="mainTableRef"></base-table>

        <el-dialog v-model="visible" title="添加用户" destroy-on-close>
            <div class="mb-2 d-flex">
                <el-input v-model="params.key" class="w-4p" placeholder="请输入关键字进行查询" @change="reloadUsers"></el-input>
            </div>
            <base-table :fields="baseFields" :dataSupplier="loadUsers" :params="params" :showSelection="true" ref="tableRef"></base-table>
            <template #footer>
                <el-button @click="visible = false" icon="Close">取消</el-button>
                <el-button type="primary" icon="Checked" @click="saveAppUsers">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
const { appId } = defineProps({
    appId: String,
});
const baseFields = [
    { label: "用户名", prop: "username" },
    { label: "昵称", prop: "nickname" },
    { label: "手机号", prop: "phone" },
    { label: "邮箱", prop: "email" },
];
const fields = [
    ...baseFields,
    { label: "操作", type: "operations", width: "120px", buttons: [{ label: "移除", icon: "Remove", action: remove, type: "danger", code: "edit" }] },
];
const visible = ref(false);
const params = ref({});
const tableRef = ref();
const mainTableRef = ref();

function loadData(params) {
    params.appId = appId;
    return app.https.post("/sys/user-app/query-by-app", params);
}

function loadUsers(params) {
    params.appId = appId;
    return app.https.post("/sys/user-app/query-no-app-user", params);
}

function showNew() {
    visible.value = true;
}

function reloadUsers() {
    tableRef.value.reload();
}

function saveAppUsers() {
    let selected = tableRef.value.getSelection();
    if (!selected.length) {
        return;
    }

    app.https
        .post("/sys/user-app/add", {
            appId,
            userIds: selected.map((item) => item.id),
        })
        .then(() => {
            app.success("操作成功");
            visible.value = false;
            mainTableRef.value.reload();
        });
}

function remove(row) {
    app.confirm("确定移除当前记录？").then(() => {
        app.https
            .post("/sys/user-app/delete", {
                appId,
                userIds: [row.id],
            })
            .then(() => {
                app.success("操作成功");
                mainTableRef.value.reload();
            });
    });
}
</script>
